package crawl

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

func fetchZhihuSearch1(query string) (string, error) {
	baseURL := "https://www.zhihu.com/search"
	params := url.Values{}
	params.Add("q", query)
	fullURL := fmt.Sprintf("%s?%s", baseURL, params.Encode())

	client := &http.Client{}
	req, err := http.NewRequest("GET", fullURL, nil)
	if err != nil {
		return "", err
	}

	// 设置User-Agent
	req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")

	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	return string(body), nil
}

// https://www.zhihu.com/api/v4/search_v3?gk_version=gz-gaokao
// &t=general
// &q=%E5%A4%A9%E4%B8%BA%E4%BB%80%E4%B9%88%E4%BC%9A%E6%89%93%E9%9B%B7
// &correction=1
// &offset=0
// &limit=20
// &filter_fields=
// &lc_idx=0
// &show_all_topics=0
// &search_source=Normal
func fetchZhihuSearch(baseURL string, query string) (string, error) {
	params := url.Values{}
	params.Add("gk_version", "gz-gaokao")
	params.Add("q", query)
	params.Add("t", "general")
	params.Add("correction", "1")
	params.Add("offset", "0")
	params.Add("limit", "20")
	params.Add("filter_fields", "")
	params.Add("lc_idx", "0")
	params.Add("show_all_topics", "0")
	params.Add("search_source", "Normal")

	fullURL := fmt.Sprintf("%s?%s", baseURL, params.Encode())

	client := &http.Client{}
	req, err := http.NewRequest("GET", fullURL, nil)
	if err != nil {
		return "", err
	}

	// 设置User-Agent
	req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
	req.Header.Set("Accept-Language", "en-US,en;q=0.9")
	req.Header.Set("accept-encoding", "gzip, deflate, br, zstd")

	req.Header.Set("x-api-version", "3.0.91")
	cookie := "d_c0=AADSHGISjRmPTqw-ToUnhSL_9f3eEpaKW6A=|1731743898"
	xZse93 := "101_3_3.0"
	apiPath := "/api/v4/search_v3?" + params.Encode()
	xZse96 := generateXZse96(apiPath, xZse93, cookie)

	req.Header.Set("xZse93", xZse93)
	req.Header.Set("Cookie", cookie)

	req.Header.Set("x-zse-96", xZse96)
	// req.Header.Set("x-zst-81", "3_2.0VhnTj77m-qofgh3TxTnq2_Qq2LYuDhV80wSL7iUZQ6nxEX20m4fBJCHMiqHPD4S1hCS974e1DrNPAQLYlUefii7q26fp2L2ZKgSfnveCgrNOQwXTt_Fqsruy6unLcbO1NukyrAuOiRnxEL2ZZrxmDucmqhPXnXFMTAoTF6RhRuLPFiL8mGxL6TcCbiNpL9FYTgg9rGeB3Cc9YggCpUOfr4LYpUCfqbxOnqtOrccTv72KcLpmQ9XKqv3Y1ck9Pge_HceLbRCMnugKZGCqkBwBIqpyeMw8IqxqJqXYbJVfLwg_zUYfbu30ucSLuhCGLw28lqFqWhoCo8cx89oV-GeGrXL_FGoxVqfzKXcqShLqPGVOwbLOvhF_ucxBqgcpjvO8NBVf8upfOqN_hU2GbDgfVhr9uJXxoJeLGUoYbee_QckmVqcf4vgLQ03KrM2mTGgqYQxOAc9CpBFLWqXB18CC")
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	return string(body), nil
}

func generateXZse96(apiPath string, xZse93 string, cookie string) string {
	// 拼接字符串
	s := xZse93 + "+" + apiPath + "+" + cookie
	// MD5 加密
	hash := md5.Sum([]byte(s))
	md5Str := hex.EncodeToString(hash[:])
	// 自定义加密（这里简化处理，实际需要逆向知乎的 JS 加密逻辑）
	encrypted := "2.0_" + md5Str // 示例，实际需要更复杂的加密
	return encrypted
}

type SearchResult struct {
	Title   string
	Link    string
	Summary string
}

func parseZhihuSearch(html string) ([]SearchResult, error) {
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
	if err != nil {
		return nil, err
	}

	var results []SearchResult
	doc.Find(".List-item").Each(func(i int, s *goquery.Selection) {
		title := s.Find("h2").Text()
		link, _ := s.Find("a").Attr("href")
		summary := s.Find(".RichText").Text()

		// 如果链接是相对路径，补全为完整URL
		if !strings.HasPrefix(link, "http") {
			link = "https://www.zhihu.com" + link
		}

		results = append(results, SearchResult{
			Title:   strings.TrimSpace(title),
			Link:    strings.TrimSpace(link),
			Summary: strings.TrimSpace(summary),
		})
	})

	return results, nil
}
